package web.manager;

import bean.Manager;
import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import util.Send;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "Login", urlPatterns = "/login/dgut")
public class Login extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        response.setContentType("text/html;charset=utf-8");
        String token = request.getParameter("token");
        String state = request.getParameter("state");

        List<NameValuePair> first = new ArrayList<>();
        first.add(new BasicNameValuePair("token", token));
        first.add(new BasicNameValuePair("appid", "javaee"));
        first.add(new BasicNameValuePair("appsecret", "b3b52e43ccfd"));
        first.add(new BasicNameValuePair("userip", request.getLocalAddr()));
        String fj = Send.post("https://cas.dgut.edu.cn/ssoapi/v2/checkToken", first);

        if (JSON.parseObject(fj).getString("message").equals("success")) {
            String access_token = JSON.parseObject(fj).getString("access_token");
            String openid = JSON.parseObject(fj).getString("openid");
            List<NameValuePair> second = new ArrayList<>();
            second.add(new BasicNameValuePair("access_token", access_token));
            second.add(new BasicNameValuePair("openid", openid));
            String sj = Send.post("https://cas.dgut.edu.cn/oauth/getUserInfo", second);

            if (JSON.parseObject(sj).getString("message") == null) {
                Manager manager = JSON.parseObject(sj, Manager.class);
                if(request.getSession().getAttribute("manager")!=null){
                    response.sendRedirect("http://localhost:8080/index.html");
                } else {
                    request.getSession().setAttribute("manager", manager);
                    response.sendRedirect("http://localhost:8080/dao/transfer");
                }
            } else {
                response.getWriter().write(JSON.parseObject(sj).getString("message"));
            }
        } else {
            response.getWriter().write(JSON.parseObject(fj).getString("message"));
        }
    }
}
